package com.jy.wms.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jy.wms.common.PropertyUtil;
import com.jy.wms.common.SetStatus;
import com.jy.wms.common.base.BaseController;
import com.jy.wms.common.base.ManySheetOneSyler;
import com.jy.wms.common.base.baseResultCode;
import com.jy.wms.pojo.SysUser;
import com.jy.wms.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: LoginController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author zzp
 * @Date 2017/10/22 10:47
 */
@RestController
@RequestMapping("/login")
@Api(value = "测试",description = "测试接口")
public class LoginController extends BaseController<LoginService,SysUser> {
    protected static Logger logger = LoggerFactory.getLogger(LoginController.class);
    @ApiOperation(value = "用户", notes = "没有条件默认查询所有；page和rows，根据分页信息查询；如果条件查询，按照规范写查询条件即可")
    @GetMapping("/MapExportExcel")
    public void exportMerchantProfitQuery(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户数据表","UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        //List<User> list = userService.findAll();
        ExportParams ep= new ExportParams("用户信息导出","用户信息导出");
        ep.setStyle(ManySheetOneSyler.class);
        List<SysUser> sysUsers=baseService.selectList(new EntityWrapper().orderBy("id"));
        Workbook workbook = ExcelExportUtil.exportExcel(ep, SysUser.class, sysUsers);
        workbook.write(response.getOutputStream());
    }
    private List<SysUser> getData() {
        List<SysUser> dataResult = new ArrayList<SysUser>();
        SysUser sysUser=new SysUser();
        SysUser sysUser2=new SysUser();
        sysUser.setId("12321");
        sysUser.setMm("zzp");
        sysUser2.setId("123221");
        sysUser2.setMm("zzp2");

        dataResult.add(sysUser);
        dataResult.add(sysUser2);

        return dataResult;
    }

    /**
     * 用户登录操作
     * @param map
     * @return
     */
    @ApiOperation(notes = "输入用户名密码即可{\"userAccount\":\"zzp\",\"userPassword\":\"123456\"}", httpMethod = "POST", value = "登陆的接口")
    @RequestMapping(value = "",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
    public  @ResponseBody
    JSONObject doLogin(@RequestBody Map<String,String> map) throws Exception {
        System.out.println(map.get("userAccount")+"============="+map.get("userPassword"));
        //1.创建subject
        Subject sub= SecurityUtils.getSubject();
        //setSessionInfo(SessionInfo.SessionBaseDB,baseData);
        UsernamePasswordToken token=new UsernamePasswordToken(map.get("userAccount"),map.get("userPassword"));
        //baseService.SessionInfo.SessionDB
        try {
            sub.login(token);
            //获取用户信息
            //SysUser sysUser= (SysUser) getSessionInfo(SessionInfo.SessionName);
            //获取角色
            //Integer [] rid=baseService.getUserByRole(sysUser.getId(),getSessionDB());
            /*if(rid.length<1){
                return SetStatus.setFunctionType(1,"error","登录失败","用户角色不存在","");
            }*/
            //获取菜单
            //com.alibaba.fastjson.JSONArray jsonArray=baseService.getMenu(rid,sysUser.getSjk());
            //setSessionInfo(SessionInfo.SessionMenu,jsonArray.toString());

            //获取授权的menu和function的code
            //List<String> mfList=baseService.getMenuAndFunctionByCode(rid,sysUser.getSjk());
            JSONObject json=new JSONObject();
            json.accumulate("user",map);
            json.accumulate("app",new baseResultCode());
            json.accumulate("menu","");
            json.accumulate("auth", "");
            return SetStatus.setFunctionType(1,"success","登录成功","登录成功",json.toString());
            // DynamicDataSource.getInstance().strDataSource();
        }catch (UnknownAccountException e){
            System.out.println("用户名不存在");
            logger.error("用户名不存在");
            return SetStatus.setFunctionType(1,"error","登录失败","用户名不存在","");
        }catch (IncorrectCredentialsException e){
            System.out.println("用户名密码错误");
            logger.error("用户名密码错误");
            return SetStatus.setFunctionType(1,"error","登录失败","用户名/密码错误","");
        }catch (Exception e){
            logger.error("登录系统错误");
            System.out.println(e.getMessage());
            return SetStatus.setFunctionType(1,"error","登录失败","系统异常","");
        }
    }

}
